﻿Imports System.Text.RegularExpressions
Imports System.Xml
Imports Llama
Imports SPF.Client.Administration
Imports SPF.Client.Schema.Collection
Imports SPF.Client.Schema.Interface
Imports Telerik.WinControls.UI
Imports Plaice
Imports System.Reflection
Imports snec_sppid_tool.PropDefSPIToPID

Module DataFromSPIToPID
    ''' <summary>
    ''' 反向数据流时,从spf上获取仪表数据。列包括2部分，一部分是固定的，一部分是xml里SPIdata章节的
    ''' </summary>
    ''' <param name="dtCreate"></param>
    ''' <param name="strDwgIDs"></param>
    ''' <remarks></remarks>
    Sub LoadSPIDataFromSPF(ByRef dtCreate As DataTable, strDwgIDs As String, ByRef XmlRootNode As XmlNode)

        MySPFWindowsClient.SPFSession = MySPFSession

        Dim objQueryReq As QueryRequest = New QueryRequest(MySPFSession, False)
        objQueryReq.AddQueryInterface("IPIDDrawing")
        objQueryReq.AddQueryPropertyWithCriteria("IObject~UID~in~(" + strDwgIDs.Replace("'", "") + ")")
        Dim objDrawingCol As IObjectDictionary = objQueryReq.ExecuteQuery.IObjectDictionary


        If System.Windows.Forms.Application.StartupPath.Length > 128 Then
            MessageBox.Show("工具所在的路径太深（超过了128个字符），请改到浅一点的路径上。再重新使用。")
            System.Windows.Forms.Application.Exit()
        End If
        Dim ReadIniColumns As String = ""

        Dim i As Integer = 0


        Dim ValveTypeInSpf As String = GetStrFromXml(XmlRootNode, "SPIDataType", "BodyType")  '阀门类型的字段
        Dim ValveActuatorTypeInSpf As String = GetStrFromXml(XmlRootNode, "SPIDataActuator", "ActuatorType") '执行机构类型
        Dim InLineDNInSpf As String = GetStrFromXml(XmlRootNode, "SPIDataDN", "DN") '
        Dim OffLineDNInSpf As String = GetStrFromXml(XmlRootNode, "SPIDataOffline", "ConnecttoProcess")
        dtCreate.Reset()
        dtCreate.Columns.Clear()
        dtCreate.Columns.Add("Proc_Func")
        dtCreate.Columns.Add("IsInline")
        dtCreate.Columns.Add("UID")
        dtCreate.Columns.Add("CMPNT_NAME")
        dtCreate.Columns.Add("OBJECT_REMOTE_UID")
        dtCreate.Columns.Add("OBJECT_REMOTE_NAME")
        dtCreate.Columns.Add("DIM_INLET_SIZE")
        'dtCreate.Columns.Add("DIM_INLET_SIZE_UID")
        dtCreate.Columns.Add("ConnToProcess")
        dtCreate.Columns.Add("执行机构")
        dtCreate.Columns.Add("阀体形式")
        Dim FixedColumnCount As Integer = dtCreate.Columns.Count
        'While i < SPIDataColumns.Count - 1
        '    'i = i + 2   'ini里的排序是，name+@+SEQ，propinpid，propinspi
        '    dtCreate.Columns.Add(SPIDataColumns.Item(i).ToString + "（SPI）")   '这个时候名字就是xmlName@subType
        '    i = i + 3
        'End While
        For Each col In SPIDataProps
            dtCreate.Columns.Add(col.PropName + "@" + col.ProcessFunction.ToString + "（SPI）")
        Next

        With objDrawingCol.GetEnumerator  '得到spf里的图纸
            Do While .MoveNext
                Dim objPIDDrawing As IObject = .Value

                Dim objRepOnPIDCol As IObjectDictionary
                objRepOnPIDCol = objPIDDrawing.GetEnd1Relationships().GetRels("DwgRepresentationComposition").GetEnd2s

                With objRepOnPIDCol.GetEnumerator   '得到spf里的Representation对象
                    Do While .MoveNext
                        Dim objRepOnPID As IObject = .Value

                        Dim objInsOnPID As IObject
                        objInsOnPID = objRepOnPID.GetEnd1Relationships().GetRel("DrawingItems").GetEnd2
                        If Not IsNothing(objInsOnPID) Then
                            If objInsOnPID.ClassDefinitionUID = "PIDInstrument" Or objInsOnPID.ClassDefinitionUID = "PIDInlineInstrument" Then
                                Dim objCDW As IObject
                                Try
                                    objCDW = objInsOnPID.GetEnd2Relationships().GetRel("SPFTEFComprisedOf").GetEnd1
                                    If Not IsNothing(objCDW) Then
                                        Dim objInsColFromSPI As IObjectDictionary
                                        objInsColFromSPI = objCDW.GetEnd1Relationships().GetRels("SPFTEFComprisedOf").GetEnd2s '这步就是最常见的CDW下面的CompriseOf

                                        With objInsColFromSPI.GetEnumerator    '得到一个cdw对象下的所有子对象（比如indexins pidins ddpins等）
                                            Do While .MoveNext
                                                Dim objInsFromSPI As IObject = .Value
                                                If objInsFromSPI.ClassDefinitionUID = "INDXInstrument" Then '找到index里的仪表
                                                    Dim dr As DataRow = dtCreate.NewRow
                                                    '固定的列
                                                    dr("Proc_Func") = GetSPFPropValue(objInsFromSPI, "IInstrument/ProcFunc", "/") 'OOTB固定的
                                                    dr("IsInline") = objInsOnPID.ClassDefinitionUID
                                                    dr("UID") = objInsFromSPI.Interfaces("IObject").Properties("UID").DisplayValue
                                                    dr("CMPNT_NAME") = objInsFromSPI.Interfaces("IObject").Properties("Name").DisplayValue
                                                    dr("OBJECT_REMOTE_UID") = objInsOnPID.Interfaces("IObject").Properties("UID").DisplayValue
                                                    dr("OBJECT_REMOTE_NAME") = objInsOnPID.Interfaces("IObject").Properties("Name").DisplayValue

                                                    Dim sInlineDN As String
                                                    sInlineDN = GetSPFPropValue(objInsFromSPI, InLineDNInSpf, "/")
                                                    If Not sInlineDN Is Nothing Then
                                                        sInlineDN = convertDN(sInlineDN)
                                                    End If
                                                    dr("DIM_INLET_SIZE") = sInlineDN





                                                    sInlineDN = GetSPFPropValue(objInsFromSPI, OffLineDNInSpf, "/")
                                                    If Not sInlineDN Is Nothing Then
                                                        sInlineDN = convertDN(sInlineDN)
                                                    End If
                                                    dr("ConnToProcess") = sInlineDN

                                                    dr("执行机构") = GetSPFPropValue(objInsFromSPI, ValveActuatorTypeInSpf, "/")
                                                    dr("阀体形式") = GetSPFPropValue(objInsFromSPI, ValveTypeInSpf, "/")



                                                    'xml配置里SPIData章节里的，灵活的
                                                    For i = FixedColumnCount To dtCreate.Columns.Count - 1
                                                        'dr(i) = GetSPFPropValue(objInsFromSPI, SPIDataColumns.Item((i - FixedColumnCount) * 3 + 2).ToString, "/")
                                                        dr(i) = GetSPFPropValue(objInsFromSPI, SPIDataProps.Item(i - FixedColumnCount).UIDSPI, "/")
                                                    Next

                                                    dtCreate.Rows.Add(dr)
                                                End If
                                            Loop
                                        End With
                                    End If
                                Catch ex As Exception
                                    Writelog(objInsOnPID.Name + "的CDW对象查询失败。", "反向数据流")
                                End Try

                            End If
                        End If
                    Loop
                End With


                ' objDDPTag.GetEnd2Relationships().GetRel("SPFTEFComprisedOf").GetEnd1()
                'Debug.Print(objDDPTag.Name)

            Loop
        End With
    End Sub
    ''' <summary>
    ''' 处理dn的单位，尽量确保其值是xxx",或者xxx mm。这样pid才能更新尺寸
    ''' </summary>
    ''' <param name="dn"></param>
    ''' <returns></returns>
    Function convertDN(dn As String)
        dn = dn.ToLower
        If InStr(dn, "in") > 0 Then
            dn = dn.Replace(" in", "").Replace("in", "") + """"


        ElseIf InStr(dn, "mm") > 0 Then
            dn = dn.Replace(" mm", "").Replace("mm", "") + " mm"
        ElseIf InStr(dn, "npt") > 0 Then
            '2022 03 03 添加
            dn = dn.Substring(0, InStr(dn, "npt") - 1).Replace(" ", "") + """"
        End If
        Return dn
    End Function
    ''' <summary>
    ''' 进行公制和英制的互转
    ''' </summary>
    ''' <param name="dn">不带单位的，纯数值</param>
    ''' <returns>带单位的</returns>
    ''' <remarks></remarks>
    Function convertDNType(dn As String, sourceType As System_UoM_Type)
        dn = dn.Trim
        Dim list_mm As New List(Of String)
        list_mm.AddRange({"3", "5", "6", "10", "12", "16", "20", "25", "32", "40", "50", "65", "80", "90", "100", "115"})
        Dim list_in As New List(Of String)
        list_in.AddRange({"1/8", "3/16", "1/4", "3/8", "1/2", "5/8", "3/4", "1", "1-1/4", "1-1/2", "2", "2-1/2", "3", "3-1/2", "4", "4-1/2"})

        If sourceType = System_UoM_Type.mm Then
            'mm to inch
            If list_mm.IndexOf(dn) > -1 Then
                'find
                dn = list_in.Item(list_mm.IndexOf(dn)) + """"
            Else
                Try
                    dn = (CDbl(dn) / 25).ToString + """"
                Catch ex As Exception

                End Try
            End If
        ElseIf sourceType = System_UoM_Type.inch Then
            'inch to mm
            If list_in.IndexOf(dn) > -1 Then
                'find
                dn = list_mm.Item(list_in.IndexOf(dn)) + " mm"
            Else
                Try
                    dn = (25 * CDbl(dn)).ToString + """"
                Catch ex As Exception

                End Try
            End If
        End If

        Return dn

    End Function
    Public Enum System_UoM_Type
        mm = 1
        inch = 2
    End Enum

    ''' <summary>
    ''' 用于存储反向数据流的普通属性字段（包括名字+@Seq、PID属性、SPF属性（包括接口））
    ''' </summary>
    Dim SPIDataProps As New List(Of PropDefSPIToPID)    'Dim SPIDataColumns As New ArrayList

    ''' <summary>
    ''' 读取Config.xml。校验属性是否存在于数据字典中。并填充5个grid的column。
    ''' </summary>
    ''' <param name="RadGridViewList">对应xml里参数的column，为Name和Name（SPI）</param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Private Function ReadConfigXml(ByRef RadGridViewList As List(Of RadGridView)) As Boolean
        Try
            Debug.Print(RadGridViewList(0).Name)
            Dim XMLPath As String = Application.StartupPath & "\Config.xml"


            Dim xmlItemTagFormat As New XmlDocument

            If Not IO.File.Exists(XMLPath) Then
                Writelog("路径中找不到Config.xml.  " + System.Reflection.MethodBase.GetCurrentMethod.Name, "反向数据流")
                Return False

            Else
                '20200525 换成xml形式的配置文件


                xmlItemTagFormat.Load(XMLPath)
                oRootNode = xmlItemTagFormat.SelectSingleNode("PIDToolConfiguration")


                '这一段就是读取常规的属性，SPIDATA这个章节里的。
                Dim oSPIDataNode As XmlNode
                oSPIDataNode = oRootNode.SelectSingleNode("SPIData")

                Dim ValveTypeInSpf As String = GetStrFromXml(oRootNode, "SPIDataType", "BodyType")  '阀门类型的字段
                Dim ValveActuatorTypeInSpf As String = GetStrFromXml(oRootNode, "SPIDataActuator", "ActuatorType") '执行机构类型
                Dim InLineDNInSpf As String = GetStrFromXml(oRootNode, "SPIDataDN", "DN") '
                Dim OffLineDNInSpf As String = GetStrFromXml(oRootNode, "SPIDataOffline", "ConnecttoProcess")



                If IsNothing(oSPIDataNode) Then
                    MessageBox.Show("请检查Config.xml的内容是否正确。")
                    Return False
                Else
                    'SPIDataColumns.Clear() : 
                    SPIDataProps.Clear()
                    For Each oAttrNode As XmlNode In oSPIDataNode.ChildNodes
                        If oAttrNode.Attributes("Name").Value <> "" And oAttrNode.Attributes("PID").Value <> "" And oAttrNode.Attributes("SPI").Value <> "" And oAttrNode.Attributes("SubType").Value <> "" Then

                            '常规属性

                            'gridview中增加列
                            If Regex.IsMatch(oAttrNode.Attributes("SubType").Value.ToString, "^[1-5]$") Then '根据subtype
                                Dim index As Integer = oAttrNode.Attributes("SubType").Value - 1
                                '校验
                                If index = myCatalogIndex.ControlValve Or index = myCatalogIndex.Flow Then '即xml里的1和2
                                    'inlinecomp 或 inlineinstrument
                                    SelectStr = <string>select * from xxxSchemaName.uniqueatts t where t.unique_name = 'IsInline' and t.entity_number in (7,41)
                                            </string>.Value.Replace("IsInline", oAttrNode.Attributes("PID").Value.ToString)
                                    Dim dtProp As New DataTable
                                    MyPIDConn.PIDReadDataByDBA(MyPIDConn.PIDPlant_DBNAME, MyPIDConn.ActivePlantPIDAppDictionary_User, SelectStr, dtProp)
                                    If dtProp.Rows.Count = 0 Then
                                        '属性不存在
                                        Writelog(oAttrNode.Attributes("PID").Value.ToString + "属性在数据字典中不存在，无法从Config.xml中加载。", "反向数据流")
                                        MessageBox.Show(oAttrNode.Attributes("PID").Value.ToString + "属性在数据字典中不存在，无法从Config.xml中加载。")
                                        dtProp = Nothing
                                        Return False
                                    End If
                                    dtProp = Nothing
                                Else
                                    'OFFLINE instrument
                                    SelectStr = <string>
select * from xxxSchemaName.uniqueatts t where t.unique_name = 'IsInline' and t.entity_number in (41)
                                            </string>.Value.Replace("IsInline", oAttrNode.Attributes("PID").Value.ToString)
                                    Dim dtProp As New DataTable
                                    MyPIDConn.PIDReadDataByDBA(MyPIDConn.PIDPlant_DBNAME, MyPIDConn.ActivePlantPIDAppDictionary_User, SelectStr, dtProp)
                                    If dtProp.Rows.Count = 0 Then
                                        '属性不存在
                                        Writelog(oAttrNode.Attributes("PID").Value.ToString + "属性在数据字典中不存在，无法从Config.xml中加载。", "反向数据流")
                                        MessageBox.Show(oAttrNode.Attributes("PID").Value.ToString + "属性在数据字典中不存在，无法从Config.xml中加载。")
                                        dtProp = Nothing
                                        Return False
                                    End If
                                    dtProp = Nothing
                                End If

                                'SPIDataColumns.Add(oAttrNode.Attributes("Name").Value + "@" + oAttrNode.Attributes("SubType").Value)
                                'SPIDataColumns.Add(oAttrNode.Attributes("PID").Value)
                                'SPIDataColumns.Add(oAttrNode.Attributes("SPI").Value)
                                SPIDataProps.Add(New PropDefSPIToPID With {.PropName = oAttrNode.Attributes("Name").Value,
                                                                           .ProcessFunction = index,
                                                                           .UIDPID = oAttrNode.Attributes("PID").Value,
                                                                           .UIDSPI = oAttrNode.Attributes("SPI").Value})



                                If RadGridViewList.Item(index).Columns.IndexOf(oAttrNode.Attributes("Name").Value) < 0 Then
                                    '该gridview还没有这一列
                                    RadGridViewList.Item(index).Columns.Add(oAttrNode.Attributes("Name").Value)
                                    RadGridViewList.Item(index).Columns.Add(oAttrNode.Attributes("Name").Value + "（SPI）")
                                End If

                            End If

                        End If
                    Next

                End If

                Return True
            End If
        Catch ex As Exception
            Writelog("执行以下过程或方法遇到问题：" + System.Reflection.MethodBase.GetCurrentMethod.Name, "反向数据流")
            Return False
        End Try

    End Function
    ''' <summary>
    ''' 反向数据流登陆SPF
    ''' </summary>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Private Function LogInSPF() As String
        '20200924   改为从SPF获取仪表 数据
        Dim sSPFPlantName As String : Dim sSPPIDSign As String
        '先把url从pid数据库中找出来
        Try

            SelectStr = <string>SELECT value FROM xxxSchemaName.T_PLANTSETTING T
WHERE T.NAME in  ('SPFURL','SPFPlantName','SPFPIDSignature')
            </string>.Value
            dtCreate.Reset()
            MyPIDConn.PIDReadDataByDBA(MyPIDConn.PIDPlant_DBNAME, MyPIDConn.PIDPlant_User, SelectStr, dtCreate)
            strSPFURL = dtCreate(0)(0).ToString
            sSPFPlantName = dtCreate(1)(0).ToString
            sSPPIDSign = dtCreate(2)(0).ToString
        Catch EX As Exception
            objPlantSettings = New LMPlantSettings
            objPlantSettings.Collect(DS)
            For Each objPlantSettingInLoop In objPlantSettings
                If objPlantSettingInLoop.Attributes("Name").value = "SPFURL" Then
                    strSPFURL = objPlantSettingInLoop.Attributes("Value").Value
                ElseIf objPlantSettingInLoop.Attributes("Name").value = "SPFPlantName" Then
                    sSPFPlantName = objPlantSettingInLoop.Attributes("Value").Value
                ElseIf objPlantSettingInLoop.Attributes("Name").value = "SPFPIDSignature" Then
                    sSPPIDSign = objPlantSettingInLoop.Attributes("Value").Value
                End If
            Next
            objPlantSettings = Nothing
        End Try

        If strSPFURL = "" Then
            Return "当前PID并未注册到SPF。"
        End If

        MySPFConn = New SPFConnection
        Try

            With MySPFConn
                .BeginInit()
                .CalledFrom = "VBClient"
                .DebugLevel = 2
                .DebugLogDirectory = Application.StartupPath
                .Sessions = Nothing
                .EndInit()
            End With

            'http://spe/spf2014server

            strSPFURL = Mid(strSPFURL, Len("://") + InStr(strSPFURL, "://"))   'spe/spf2014server
            Dim mstrHostName As String = Mid(strSPFURL, 1, InStr(strSPFURL, "/") - 1) '"SPE"  'Web Host    
            Dim mstrSiteName As String = Mid(strSPFURL, InStr(strSPFURL, "/") + 1) '"spf2014server"     'Web Directory
            MySPFServer = New SPFServer(mstrHostName & ":" & mstrSiteName, mstrHostName, mstrSiteName)
            Dim index As Integer = MySPFConn.Servers.Add(MySPFServer)
            MySPFConn.Servers.SelectedIndex = index


            SPFLogin.ShowDialog()
            If blnIWA Then
                MySPFServer.Credentials = System.Net.CredentialCache.DefaultCredentials
                MySPFSession = MySPFConn.Login("", "AUTOLOGON")
            Else
                MySPFSession = MySPFConn.Login(sSpfUser, sSpfPs)

            End If



            '
            Dim RESULT = MySPFServer.IsAuthenticated_Trusted()
            Debug.Print("")
        Catch ex As Exception

            Return "访问SPF服务器有异常。具体为：" + vbNewLine + ex.Message



        End Try
        Return ""
    End Function

    ''' <summary>
    ''' 更新阀门的尺寸（NominalDiameter属性以及每个pipingport的NominalDiameter属性）
    ''' </summary>
    ''' <param name="SPID"></param>
    ''' <param name="OldSize"></param>
    ''' <param name="NewSize"></param>
    ''' <param name="UID"></param>
    ''' <param name="UIDInSPI"></param>
    Public Sub UpdateSize(SPID As String, OldSize As String, NewSize As String)

        DS.BeginTransaction()
        Dim objInst As Object
        Select Case DS.GetModelItem(SPID).AsLMAItem.ItemType.ToUpper
            Case "INSTRUMENT"
                objInst = DS.GetInstrument(SPID)
            Case "PIPINGCOMP"
                objInst = DS.GetPipingComp(SPID)
            Case Else
                Exit Sub
        End Select


        If Not IsNothing(objInst) Then
            If NewSize <> "0" Then
                objInst.Attributes("NominalDiameter").Value = NewSize
                For Each objPipingPoint As LMPipingPoint In objInst.PipingPoints
                    objPipingPoint.Attributes("NominalDiameter").Value = NewSize
                    objPipingPoint.Commit()   'commit不能离属性修改的属性太远
                    '找两个端点的坐标，放置大小头
                Next
                Writelog("仪表 [" & objInst.Attributes("ItemTag").Value & "], 口径由 [" & OldSize & "] 更新为 [" & objInst.Attributes("NominalDiameter").Value & "]", "反向数据流")
                '还需要end 1 和 end 2 的两个size
            End If
            objInst.Commit()
            DS.CommitTransaction()
        End If





    End Sub
    ''' <summary>
    ''' 1，代表执行机构。2，代表阀门类型。3，代表流量计类型
    ''' </summary>
    ''' <param name="SPID">仪表的id</param>
    ''' <param name="NewFileName"></param>
    ''' <param name="mode"></param>
    ''' <remarks></remarks>
    Public Sub UpdateSymbolWithDwgOpened(SPID As String, NewFileName As String, mode As Integer)
        Dim sym_spid As String = ""
        If mode = 1 Then 'actuator
            SelectStr = <string>select t2.itemtag,t8.sp_id ActSymID
        from xxxSchemaName.t_instrument t1
        join xxxSchemaName.t_modelitem t3 on t1.sp_id=t3.sp_id
        join xxxSchemaName.t_plantitem t2 on t1.sp_id=t2.sp_id
        join xxxSchemaName.t_representation t6 on t6.sp_modelitemid=t1.sp_id
        left join xxxSchemaName.t_inlinecomp t4 on t4.sp_id=t1.sp_id
    join xxxSchemaName.T_Drawing t5 on t5.SP_ID=t6.SP_DrawingID
    left join xxxSchemaName.t_plantitem t7 on t2.sp_id=t7.sp_partofid
    left join xxxSchemaName.t_representation t8 on t8.sp_modelitemid=t7.sp_id
        where t2.sp_id= 'xxxSPID'
</string>.Value
        ElseIf mode = 2 Or mode = 3 Then 'bodytype
            SelectStr = <string>
select t2.itemtag,t6.sp_id SymID,t6.filename FileName
        from xxxSchemaName.t_instrument t1
        join xxxSchemaName.t_plantitem t2 on t1.sp_id=t2.sp_id
        join xxxSchemaName.t_modelitem t3 on t1.sp_id=t3.sp_id
        join xxxSchemaName.t_representation t6 on t6.sp_modelitemid=t1.sp_id
where t2.sp_id= 'xxxSPID'   
</string>.Value
        End If

        SelectStr = SelectStr.Replace("xxxSPID", SPID)
        Dim dtCreatePID As New DataTable
        MyPIDConn.PIDReadDataByDBA(MyPIDConn.PIDPlant_DBNAME, MyPIDConn.ActivePlantPIDApp_User, SelectStr, dtCreatePID)
        Try
            If dtCreatePID.Rows.Count = 0 Then
                Exit Sub
            End If

            If mode = 1 Then
                sym_spid = dtCreatePID(0)("actsymid")
            ElseIf mode = 2 Or mode = 3 Then
                sym_spid = dtCreatePID(0)("symid")
            End If
            '2022 03 03，改为直接数据库修改，客户接受re create
            SelectStr = String.Format("UPDATE xxxSchemaName.T_REPRESENTATION set filename='{0}' where SP_ID='{1}' and representationtype='13'", NewFileName, sym_spid)
            MyPIDConn.PIDUpdateDataByDBA(MyPIDConn.PIDPlant_DBNAME, MyPIDConn.ActivePlantPIDApp_User, SelectStr)

            If mode = 1 Then 'actuator
                Writelog("仪表 [" & dtCreatePID(0)(0) & "],执行机构 ,更新为 [" & NewFileName & "]", "反向数据流")
            ElseIf mode = 2 Then
                Writelog("仪表 [" & dtCreatePID(0)(0) & "],阀体类型  ,更新为 [" & NewFileName & "]", "反向数据流")
            ElseIf mode = 3 Then
                Writelog("仪表 [" & dtCreatePID(0)(0) & "],流量计形式 ,更新为 [" & NewFileName & "]", "反向数据流")
            End If
        Catch ex As Exception
            If mode = 1 Then 'actuator
                Writelog("仪表 [" & dtCreatePID(0)(0) & "],执行机构 ,未能更新,因为 [" & ex.Message & "]", "反向数据流")
            ElseIf mode = 2 Then
                Writelog("仪表 [" & dtCreatePID(0)(0) & "],阀体类型 ,未能更新,因为 [" & ex.Message & "]", "反向数据流")
            ElseIf mode = 3 Then
                Writelog("仪表 [" & dtCreatePID(0)(0) & "],流量计形式 ,未能更新,因为 [" & ex.Message & "]", "反向数据流")
            End If

        End Try
    End Sub

    ''' <summary>
    ''' 更新config.xml里的属性
    ''' </summary>
    ''' <param name="SPID">仪表的ID</param>
    ''' <param name="NewValue"></param>
    ''' <param name="PropNameInPID">从SPIDataColumns里找出来的，对应gridview里某列name+@+seq，再加1</param>
    ''' <remarks></remarks>
    Public Sub UpdateMoreProp(SPID As String, NewValue As String, PropNameInPID As String)
        DS.BeginTransaction()
        Dim objInst As LMInstrument
        Dim oldSize As String
        Dim NumberInStr As String
        Dim AlphaInStr As String
        Dim OldValueUoM As String
        objInst = DS.GetInstrument(SPID)
        If IsNothing(objInst) Then
            Exit Sub
        End If
        Try
            Dim objAttr As LMAAttribute
            objAttr = objInst.Attributes(PropNameInPID)
            If IsNothing(objAttr) Then
                Writelog("仪表 [" & objInst.Attributes("ItemTag").Value & "],属性 [" & PropNameInPID & "] 不存在。无法更新。", "反向数据流")
                Exit Sub
            End If
        Catch ex As Exception
            Writelog("仪表 [" & objInst.Attributes("ItemTag").Value & "],属性 [" & PropNameInPID & "] 无法更新。原因：" + ex.Message, "反向数据流")
            Exit Sub
        End Try


        If objInst.Attributes(PropNameInPID).Value Is System.DBNull.Value Then
            oldSize = ""
        Else
            oldSize = objInst.Attributes(PropNameInPID).Value
        End If
        If IsNumeric(Mid(NewValue, 1, 1)) Then   '如果是数值
            '可以考虑加空格，增加写入的成功率
            NumberInStr = Regex.Replace(NewValue, "[^\d.\d]", "")
            AlphaInStr = Regex.Replace(NewValue, "[\d.\d]", "")
            Try
                OldValueUoM = Regex.Replace(objInst.Attributes(PropNameInPID).Value, "[\d.\d]", "")
                If AlphaInStr.ToUpper = OldValueUoM.ToUpper Then
                    NewValue = NumberInStr.Replace(" ", "") & " " & OldValueUoM.Replace(" ", "")
                Else
                    'uom is not the same
                End If
                'Dim X = objInst.Attributes(PropNameInPID).ISPAttribute.Format.FormatElements.Count
                'For I = 1 To X
                '    Debug.Print(objInst.Attributes(PropNameInPID).ISPAttribute.Format.FormatElements.Item(I).Name)
                'Next
                'Dim Y = objInst.Attributes(PropNameInPID).ISPAttribute.Format.FormatType

            Catch ex As Exception
                NewValue = NumberInStr.Replace(" ", "") & " " & AlphaInStr.Replace(" ", "")
            End Try


        Else
            '如果本来就是字母开头的就算了

        End If
        Try
            '考虑单位  比如kpa和kPa的匹配

            objInst.Attributes(PropNameInPID).Value = NewValue
            objInst.Commit()
            If objInst.Attributes(PropNameInPID).Value = NewValue Then
                Writelog("仪表 [" & objInst.Attributes("ItemTag").Value & "],属性 [" & PropNameInPID & "] ,由 [" & oldSize & "] 更新为 [" & objInst.Attributes(PropNameInPID).Value & "]", "反向数据流")
            Else
                Writelog("仪表 [" & objInst.Attributes("ItemTag").Value & "],属性 [" & PropNameInPID & "] ,未能由 [" & oldSize & "] 更新为 [" & NewValue & "]", "反向数据流")
            End If
        Catch
            Writelog("仪表 [" & objInst.Attributes("ItemTag").Value & "],属性 [" & PropNameInPID & "] ,未能由 [" & oldSize & "] 更新为 [" & NewValue & "]", "反向数据流")

        End Try

        DS.CommitTransaction()
        objInst = Nothing

    End Sub
    ''' <summary>
    ''' 
    ''' </summary>
    ''' <param name="OldValue">经历过convertDN的处理，都是标准的" 或者  mm</param>
    ''' <param name="NewValue"></param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Public Function SizeSame(OldValue As String, ByRef NewValue As String) As Boolean




        Dim UoMNew As String
        Dim UoMOld As String
        '简单点，直接找第一个字母，尾部找 mm或者"（这部分已经通过函数 convertDN 在从spf读取数据时处理过了）
        ' 22 mm,    33",     1/2",    1-1/2" 这4种
        NewValue = NewValue.ToLower

        If Regex.IsMatch(NewValue, "[\d]+-[\d]/[\d]""") Then   '1-1/2"
            NewValue = Regex.Match(NewValue, "[\d]+-[\d]/[\d]""").Value
            UoMNew = """"
        ElseIf Regex.IsMatch(NewValue, "[\d]/[\d]""") Then
            NewValue = Regex.Match(NewValue, "[\d]/[\d]""").Value '1/2"
            UoMNew = """"
        ElseIf Regex.IsMatch(NewValue, "[\d]+ mm") Then
            NewValue = Regex.Match(NewValue, "[\d]+ mm").Value '22 mm
            UoMNew = " mm"
        ElseIf Regex.IsMatch(NewValue, "[\d]+""") Then
            NewValue = Regex.Match(NewValue, "[\d]+""").Value   '33"
            UoMNew = """"
            'ElseIf Regex.IsMatch(NewValue, "[\d]+") Then
            '    NewValue = Regex.Match(NewValue, "[\d]+").Value   '33
        Else
            Return False
        End If

        If UoMNew = " mm" And RadForm1.DN_IN.IsChecked Then
            'spi是公制，但是pid是英制
            NewValue = convertDNType(NewValue.Replace(" mm", ""), System_UoM_Type.mm)
            UoMNew = """"
        ElseIf UoMNew = """" And RadForm1.DN_mm.IsChecked Then
            'spi是英制，但是pid是公制
            NewValue = convertDNType(NewValue.Replace("""", ""), System_UoM_Type.inch)
            UoMNew = " mm"
        End If


        If InStr(OldValue, """") > 0 Then
            UoMOld = """"
        ElseIf InStr(OldValue, " mm") > 0 Then
            UoMOld = " mm"
        Else
            Return False
        End If

        If UoMNew <> UoMOld Then
            Try
                '比如1-1/2 ，这种就没办法去做乘法

                If UoMOld = " mm" And UoMNew = """" Then
                    If (CDbl(OldValue.Replace(" mm", "")) = 25 * CDbl(NewValue.Replace("""", "")) Or CDbl(OldValue.Replace(" mm", "")) = 25.4 * CDbl(NewValue.Replace("""", ""))) Then
                        '4" = 100 mm， 这种情况时， 也是相同的
                        Return True
                    Else
                        Return False
                    End If

                ElseIf UoMOld = """" And UoMNew = " mm" Then
                    If (CDbl(NewValue.Replace(" mm", "")) = 25 * CDbl(OldValue.Replace("""", "")) Or CDbl(NewValue.Replace(" mm", "")) = 25.4 * CDbl(OldValue.Replace("""", ""))) Then
                        '100 mm = 4"，这种情况时，也是相同的
                        Return True
                    Else
                        Return False
                    End If

                Else
                    Return False
                    '到这里，就是数值不等,单位也不同的情况
                End If
            Catch ex As Exception
                Return False
            End Try
        Else
            If OldValue = NewValue Then
                Return True
            Else
                Return False
            End If

        End If



    End Function
    ''' <summary>
    ''' 
    ''' </summary>
    ''' <param name="TagName"></param>
    ''' <param name="SPID">分支管的id</param>
    ''' <param name="OldSize"></param>
    ''' <param name="NewValue"></param>
    ''' <remarks></remarks>
    Public Sub UpdateConntoProcessSize(TagName As String, SPIDs As String, OldSize As String, NewValue As String, InsId As String)
        If NewValue = "" Then
            Exit Sub
        End If



        For Each startConnId In SPIDs.Split(",")
            Dim OldConns As New List(Of String)
            Dim OldComps As New List(Of String)
            Dim OldBranchs As New List(Of String)
            Dim res = AutoBreak.Class1.NaviCore(MyPIDConn, startConnId, InsId, OldConns, OldBranchs, OldComps, AutoBreak.Class1.NaviMode.BackMainRun)
            If res = "err" Then
                OldConns.Clear() : OldComps.Clear() : OldBranchs.Clear()
                res = AutoBreak.Class1.NaviCore(MyPIDConn, startConnId, InsId, OldConns, OldBranchs, OldComps, AutoBreak.Class1.NaviMode.FindEnd)
                If res = "err" Then
                    Continue For
                Else
                    Dim oNozzle As LMNozzle = DS.GetNozzle(res)
                    If IsNothing(oNozzle) Then
                        'NOT  connect to nozzle
                        Continue For
                    End If

                End If

            End If
            For Each spid In OldComps
                UpdateSize(spid, "OLD", NewValue)
            Next
            Dim blnErr As Boolean = False
            For Each spid In OldConns
                Dim objPipe As LMPipeRun
                Dim oConn As LMConnector
                oConn = DS.GetConnector(spid)
                If oConn Is Nothing Then
                    Continue For
                End If
                objPipe = DS.GetPipeRun(oConn.ModelItemID)
                If IsNothing(objPipe) Then
                    Writelog("仪表 [" & TagName & "] " & ", 分支管通径, 找不到分支管对象" & spid, "反向数据流")
                    'Exit Sub
                    Continue For
                End If
                DS.BeginTransaction()
                If objPipe.Attributes("NominalDiameter").Value Is System.DBNull.Value Then
                    OldSize = ""
                Else
                    OldSize = objPipe.Attributes("NominalDiameter").Value
                End If

                'If Not SizeSame(OldSize, NewValue) Then
                Try
                    objPipe.Attributes("NominalDiameter").Value = NewValue
                    objPipe.Commit()
                Catch ex As Exception
                    blnErr = True
                    Writelog("仪表 [" & TagName & "] " & ", 分支管的一段" + spid + ",通径未能由 [" & OldSize & "] 更新为 [" & NewValue & "]", "反向数据流")
                    DS.CommitTransaction()
                End Try
                DS.CommitTransaction()
                objPipe = Nothing
                'End If
            Next
            If True Then
                Writelog("仪表 [" & TagName & "] " & ", 分支管通径, 至少有一段未能由 [" & OldSize & "] 更新为 [" & NewValue & "]", "反向数据流")
            Else
                Writelog("仪表 [" & TagName & "] " & ", 分支管通径, 由 [" & OldSize & "] 更新为 [" & NewValue & "]", "反向数据流")
            End If

        Next

        'If IsNumeric(Mid(NewValue, 1, 1)) Then
        '    NewValue = NewValue.ToLower
        '    If InStr(NewValue, "mm") > 0 Or InStr(NewValue, " mm") > 0 Then
        '        'mm
        '        '可以考虑加空格，增加写入的成功率
        '        NumberInStr = Regex.Replace(NewValue, "[^\d.\d]", "")
        '        AlphaInStr = Regex.Replace(NewValue, "[\d.\d]", "")
        '        NewValue = NumberInStr.Replace(" ", "") & " " & AlphaInStr.Replace(" ", "")
        '    ElseIf InStr(NewValue, "in") > 0 Or InStr(NewValue, """") > 0 Then
        '        NumberInStr = Regex.Replace(NewValue, "[^\d.\d]", "")
        '        AlphaInStr = Regex.Replace(NewValue, "[\d.\d]", "").Replace("in", """")

        '        NewValue = NumberInStr.Replace(" ", "") & AlphaInStr.Replace(" ", "")
        '    Else
        '        'in
        '        NumberInStr = Regex.Replace(NewValue, "[^\d.\d]", "")
        '        AlphaInStr = Regex.Replace(NewValue, "[\d.\d]", "")
        '        NewValue = NumberInStr.Replace(" ", "") & " " & AlphaInStr.Replace(" ", "")
        '    End If
        'Else
        '    '如果本来就是字母开头的就算了

        'End If
        '已经在调用时，判断过 old new值不等

    End Sub

    ''' <summary>
    ''' 
    ''' </summary>
    ''' <param name="RadPageGridList"></param>
    ''' <param name="Mode"></param>
    ''' <remarks></remarks>
    Sub UpdateData(ByRef RadPageGridList As List(Of RadGridView), Mode As Integer)
        DS = New LMADataSource
        DS.PropagateChanges = False   '一定要手动给他设置false才行,即使原来默认的值是false,也必须手动设置后才能生效

        '5个gridview来分别处理

        'Dim sDrawigName As String

        For i = 0 To DrawingCol.Count - 1
            'sDrawigName = DS.GetDrawing(DrawingCol.Item(i).ToString).Name.ToString

            '-----------2022 03 10，改为当前sheet中的选中行
            Select Case RadForm1.RadPageView1.SelectedPage.TabIndex
                Case myCatalogIndex.ControlValve
                    '---------阀门
                    With RadPageGridList.Item(myCatalogIndex.ControlValve)

                        For Each SelectedRow As GridViewRowInfo In .Rows.AsEnumerable().Where(Function(x) x.Cells(0).Value = True).ToList
                            Try
                                DS.BeginTransaction()
                                Dim SP_ID As String = SelectedRow.Cells("序号").Tag
                                Dim Size As String : Dim SizeInSPI As String
                                With SelectedRow
                                    ''-----------属于当前打开的图纸的
                                    'If .Cells("图纸号").Value.ToString <> sDrawigName.Substring(0, Len(sDrawigName) - 4) And .Cells("图纸号").Value.ToString <> sDrawigName Then
                                    '    Continue For
                                    'End If

                                    If Not SelectedRow.Cells("公称直径（SPI）").Value Is Nothing Then   'spi的size为空时
                                        '1. 阀门通径
                                        If .Cells("公称直径（SPI）").Value.ToString <> "" Then
                                            'If (InStr(.Cells("公称直径（SPI）").Value.ToString, """") > 0 And InStr(.Cells("公称直径").Value.ToString, """") > 0) Or
                                            '       (InStr(.Cells("公称直径（SPI）").Value.ToString, " mm") > 0 And InStr(.Cells("公称直径").Value.ToString, " mm") > 0) Then
                                            '    UIDInSPI = Regex.Replace(.Cells("公称直径（SPI）").Value.ToString, "\d", "")
                                            '    UID = UIDInSPI
                                            '    '到这里，就是数值不等，单位相同的情况
                                            '    SizeInSPI = Regex.Replace(.Cells("公称直径（SPI）").Value.ToString, "\D", "")
                                            '    UpdateSize(SP_ID, "N/A", SizeInSPI, UID, UIDInSPI)
                                            'Else
                                            '    UID = Regex.Replace(.Cells("公称直径").Value.ToString, "\d", "")
                                            '    UIDInSPI = Regex.Replace(.Cells("公称直径（SPI）").Value.ToString, "\d", "")
                                            '    If UID <> UIDInSPI Then
                                            '        '单位不一样
                                            '        '再考虑下数值是否刚好是25  or  25.4倍数的情况
                                            '        Size = Trim(System.Text.RegularExpressions.Regex.Replace(.Cells("公称直径").Value.ToString, "\D", ""))
                                            '        SizeInSPI = Trim(System.Text.RegularExpressions.Regex.Replace(.Cells("公称直径（SPI）").Value.ToString, "\D", ""))

                                            '        If UID = " mm" And UIDInSPI = """" And (CDbl(Size) = 25 * CDbl(SizeInSPI) Or CDbl(Size) = 25.4 * CDbl(SizeInSPI)) Then
                                            '            '4" = 100 mm， 这种情况时， 也是相同的
                                            '        ElseIf UID = """" And UIDInSPI = " mm" And (CDbl(SizeInSPI) = 25 * CDbl(Size) Or CDbl(SizeInSPI) = 25.4 * CDbl(Size)) Then
                                            '            '100 mm = 4"，这种情况时，也是相同的
                                            '        Else
                                            '            '到这里，就是数值不等,单位也不同的情况
                                            '            UpdateSize(SP_ID, Size, SizeInSPI, UID, UIDInSPI)
                                            '        End If
                                            '    Else
                                            '        '到这里，就是数值不等，单位相同的情况，因为可能都是隐藏了单位
                                            '        Size = Trim(System.Text.RegularExpressions.Regex.Replace(.Cells("公称直径").Value.ToString, "\D", ""))
                                            '        SizeInSPI = Trim(System.Text.RegularExpressions.Regex.Replace(.Cells("公称直径（SPI）").Value.ToString, "\D", ""))
                                            '        UpdateSize(SP_ID, Size, SizeInSPI, UID, UIDInSPI)
                                            '    End If
                                            'End If
                                            'Size = Nothing : SizeInSPI = Nothing
                                            Size = .Cells("公称直径").Value.ToString : SizeInSPI = .Cells("公称直径（SPI）").Value.ToString
                                            If Not SizeSame(Size, SizeInSPI) Then
                                                UpdateSize(SP_ID, Size, SizeInSPI)
                                            End If
                                        End If
                                    End If
2:                                  '2.阀门的执行机构
                                    If Not IsDBNull(.Cells("执行机构").Value) Then
                                        '2021 12 20，执行机构可能为空
                                        If Not .Cells("执行机构").Value = "" Then
                                            '2020 05 25 改为xml配置
                                            Dim Enum4PIDSym As String
                                            Enum4PIDSym = GetStrFromXml(oRootNode, "SPIDataActuator", "Enum", .Cells("执行机构（SPI）").Value.ToString)
                                            If Enum4PIDSym <> "Error" And Mid(Enum4PIDSym, 1 + InStrRev(Enum4PIDSym, "\")) <> .Cells("执行机构").Value Then
                                                UpdateSymbolWithDwgOpened(SP_ID, Enum4PIDSym, 1)
                                            End If
                                        End If
                                    End If

                                    '3.阀门的阀体   20200927取消
                                    If Not IsDBNull(.Cells("阀体形式").Value) Then
                                        'ini中没找到  同时   找到了，但是缺匹配的话
                                        '2020 05 25 改为xml配置
                                        Dim Enum4PIDSym As String
                                        Enum4PIDSym = GetStrFromXml(oRootNode, "SPIDataType", "Enum", .Cells("阀体形式（SPI）").Value.ToString)
                                        If Enum4PIDSym <> "Error" And Mid(Enum4PIDSym, 1 + InStrRev(Enum4PIDSym, "\")) <> .Cells("阀体形式").Value Then
                                            UpdateSymbolWithDwgOpened(SP_ID, Enum4PIDSym, 2)
                                        End If
                                    End If
                                End With

                                'Else
                                '    '离线仪表的情况
                                '    SP_ID = SelectedRow.Cells("SP_ID").Value     '中间conntoprocess线的ID
                                '    Size = SelectedRow.Cells("conntoprocess").Value
                                '    SizeInSPI = SelectedRow.Cells("conntoprocessinspi").Value
                                '    If Size <> SizeInSPI Then
                                '        UpdateConntoProcessSize(SelectedRow.Cells("ItemTag").Value, SP_ID, Size, SizeInSPI)
                                '    End If

                                'End If
                                '***********Config.xml中的其他属性
                                For j = .Columns.IndexOf("图纸号") + 1 To .Columns.Count - 1 Step 2
                                    If Not SelectedRow.Cells(j + 1).Value Is Nothing Then  'spi没有值，都是不会更新的
                                        'If SPIDataColumns.IndexOf(.Columns(j).Name + "@1") > -1 Then
                                        '    UpdateMoreProp(SP_ID, SelectedRow.Cells(j + 1).Value.ToString, SPIDataColumns(SPIDataColumns.IndexOf(.Columns(j).Name + "@1") + 1))
                                        'End If
                                        Dim PropName = .Columns(j).Name
                                        Dim FoundProps = SPIDataProps.Where(Function(x) x.ProcessFunction = myCatalogIndex.ControlValve And x.PropName = PropName)
                                        If FoundProps.Count = 1 Then
                                            UpdateMoreProp(SP_ID, SelectedRow.Cells(j + 1).Value.ToString, FoundProps(0).UIDPID)
                                        End If
                                    End If
                                Next



                                DS.CommitTransaction()
                            Catch ex As Exception
                                Debug.Print(ex.Message)
                            End Try

                            SelectedRow.Cells(0).Value = False
                        Next

                    End With
                Case myCatalogIndex.Flow
                    '---------流量
                    With RadPageGridList.Item(myCatalogIndex.Flow)

                        For Each SelectedRow As GridViewRowInfo In .Rows.AsEnumerable().Where(Function(x) x.Cells(0).Value = True).ToList
                            Try
                                DS.BeginTransaction()
                                Dim SP_ID As String = SelectedRow.Cells("序号").Tag
                                Dim Size As String : Dim SizeInSPI As String
                                With SelectedRow
                                    ''-----------属于当前打开的图纸的
                                    'If .Cells("图纸号").Value.ToString <> sDrawigName.Substring(0, Len(sDrawigName) - 4) And .Cells("图纸号").Value.ToString <> sDrawigName Then
                                    '    Continue For
                                    'End If


                                    If Not SelectedRow.Cells("公称直径（SPI）").Value Is Nothing Then   'spi的size为空时
                                        '1. 阀门通径
                                        If .Cells("公称直径（SPI）").Value.ToString <> "" Then
                                            'If (InStr(.Cells("公称直径（SPI）").Value.ToString, """") > 0 And InStr(.Cells("公称直径").Value.ToString, """") > 0) Or
                                            '       (InStr(.Cells("公称直径（SPI）").Value.ToString, " mm") > 0 And InStr(.Cells("公称直径").Value.ToString, " mm") > 0) Then
                                            '    UIDInSPI = Regex.Replace(.Cells("公称直径（SPI）").Value.ToString, "\d", "")
                                            '    UID = UIDInSPI
                                            '    '到这里，就是数值不等，单位相同的情况
                                            '    SizeInSPI = Regex.Replace(.Cells("公称直径（SPI）").Value.ToString, "\D", "")
                                            '    UpdateSize(SP_ID, "N/A", SizeInSPI, UID, UIDInSPI)
                                            'Else
                                            '    UID = Regex.Replace(.Cells("公称直径").Value.ToString, "\d", "")
                                            '    UIDInSPI = Regex.Replace(.Cells("公称直径（SPI）").Value.ToString, "\d", "")
                                            '    If UID <> UIDInSPI Then
                                            '        '单位不一样
                                            '        '再考虑下数值是否刚好是25  or  25.4倍数的情况
                                            '        Size = Trim(System.Text.RegularExpressions.Regex.Replace(.Cells("公称直径").Value.ToString, "\D", ""))
                                            '        SizeInSPI = Trim(System.Text.RegularExpressions.Regex.Replace(.Cells("公称直径（SPI）").Value.ToString, "\D", ""))

                                            '        If UID = " mm" And UIDInSPI = """" And (CDbl(Size) = 25 * CDbl(SizeInSPI) Or CDbl(Size) = 25.4 * CDbl(SizeInSPI)) Then
                                            '            '4" = 100 mm， 这种情况时， 也是相同的
                                            '        ElseIf UID = """" And UIDInSPI = " mm" And (CDbl(SizeInSPI) = 25 * CDbl(Size) Or CDbl(SizeInSPI) = 25.4 * CDbl(Size)) Then
                                            '            '100 mm = 4"，这种情况时，也是相同的
                                            '        Else
                                            '            '到这里，就是数值不等,单位也不同的情况
                                            '            UpdateSize(SP_ID, Size, SizeInSPI, UID, UIDInSPI)
                                            '        End If
                                            '    Else
                                            '        '到这里，就是数值不等，单位相同的情况，因为可能都是隐藏了单位
                                            '        Size = Trim(System.Text.RegularExpressions.Regex.Replace(.Cells("公称直径").Value.ToString, "\D", ""))
                                            '        SizeInSPI = Trim(System.Text.RegularExpressions.Regex.Replace(.Cells("公称直径（SPI）").Value.ToString, "\D", ""))
                                            '        UpdateSize(SP_ID, Size, SizeInSPI, UID, UIDInSPI)
                                            '    End If
                                            'End If
                                            'Size = Nothing : SizeInSPI = Nothing
                                            Size = .Cells("公称直径").Value.ToString : SizeInSPI = .Cells("公称直径（SPI）").Value.ToString
                                            If Not SizeSame(Size, SizeInSPI) Then
                                                UpdateSize(SP_ID, Size, SizeInSPI)
                                            End If
                                        End If

                                        '2.流量计类型
                                        If Not IsDBNull(.Cells("仪表类型").Value) Then
                                            'ini中没找到  同时   找到了，但是缺匹配的话
                                            '2020 05 25 改为xml配置
                                            Dim Enum4PIDSym As String
                                            Enum4PIDSym = GetStrFromXml(oRootNode, "SPIDataType", "Enum", .Cells("仪表类型（SPI）").Value.ToString)
                                            If Enum4PIDSym <> "Error" And Mid(Enum4PIDSym, 1 + InStrRev(Enum4PIDSym, "\")) <> .Cells("仪表类型").Value Then
                                                UpdateSymbolWithDwgOpened(SP_ID, Enum4PIDSym, 3)
                                            End If
                                        End If
                                    End If


                                End With

                                'Else
                                '    '离线仪表的情况
                                '    SP_ID = SelectedRow.Cells("SP_ID").Value     '中间conntoprocess线的ID
                                '    Size = SelectedRow.Cells("conntoprocess").Value
                                '    SizeInSPI = SelectedRow.Cells("conntoprocessinspi").Value
                                '    If Size <> SizeInSPI Then
                                '        UpdateConntoProcessSize(SelectedRow.Cells("ItemTag").Value, SP_ID, Size, SizeInSPI)
                                '    End If

                                'End If
                                '***********Config.xml中的其他属性
                                For j = .Columns.IndexOf("图纸号") + 1 To .Columns.Count - 1 Step 2
                                    If Not SelectedRow.Cells(j + 1).Value Is Nothing Then
                                        'If SPIDataColumns.IndexOf(.Columns(j).Name + "@2") > -1 Then
                                        '    UpdateMoreProp(SP_ID, SelectedRow.Cells(j + 1).Value.ToString, SPIDataColumns(SPIDataColumns.IndexOf(.Columns(j).Name + "@2") + 1))
                                        'End If
                                        Dim PropName = .Columns(j).Name
                                        Dim FoundProps = SPIDataProps.Where(Function(x) x.ProcessFunction = myCatalogIndex.Flow And x.PropName = PropName)
                                        If FoundProps.Count = 1 Then
                                            UpdateMoreProp(SP_ID, SelectedRow.Cells(j + 1).Value.ToString, FoundProps(0).UIDPID)
                                        End If
                                    End If
                                Next


                                DS.CommitTransaction()
                            Catch

                            End Try
                            SelectedRow.Cells(0).Value = False
                        Next

                    End With
                Case myCatalogIndex.Temperature
                    '---------温度
                    With RadPageGridList.Item(myCatalogIndex.Temperature)

                        For Each SelectedRow As GridViewRowInfo In .Rows.AsEnumerable().Where(Function(x) x.Cells(0).Value = True).ToList
                            Try
                                DS.BeginTransaction()
                                Dim SP_ID As String = SelectedRow.Cells("序号").Tag
                                Dim ConnRun_SP_ID As String = SelectedRow.Cells("分支管").Tag     '中间conntoprocess线的ID
                                Dim Size As String : Dim SizeInSPI As String
                                With SelectedRow
                                    Size = SelectedRow.Cells("分支管").Value
                                    SizeInSPI = SelectedRow.Cells("分支管（SPI）").Value
                                    If Not SizeSame(Size, SizeInSPI) Then
                                        UpdateConntoProcessSize(SelectedRow.Cells("位号").Value, ConnRun_SP_ID, Size, SizeInSPI, SP_ID)
                                    End If


                                End With

                                '***********Config.xml中的其他属性
                                For j = .Columns.IndexOf("图纸号") + 1 To .Columns.Count - 1 Step 2
                                    If Not SelectedRow.Cells(j + 1).Value Is Nothing Then
                                        'If SPIDataColumns.IndexOf(.Columns(j).Name + "@3") > -1 Then
                                        '    UpdateMoreProp(SP_ID, SelectedRow.Cells(j + 1).Value.ToString, SPIDataColumns(SPIDataColumns.IndexOf(.Columns(j).Name + "@3") + 1))

                                        'End If
                                        Dim PropName = .Columns(j).Name
                                        Dim FoundProps = SPIDataProps.Where(Function(x) x.ProcessFunction = myCatalogIndex.Temperature And x.PropName = PropName)
                                        If FoundProps.Count = 1 Then
                                            UpdateMoreProp(SP_ID, SelectedRow.Cells(j + 1).Value.ToString, FoundProps(0).UIDPID)
                                        End If
                                    End If
                                Next


                                DS.CommitTransaction()
                            Catch

                            End Try
                            SelectedRow.Cells(0).Value = False
                        Next

                    End With
                Case myCatalogIndex.Pressure
                    '---------压力
                    With RadPageGridList.Item(myCatalogIndex.Pressure)
                        For Each SelectedRow As GridViewRowInfo In .Rows.AsEnumerable().Where(Function(x) x.Cells(0).Value = True).ToList
                            Try
                                DS.BeginTransaction()
                                Dim SP_ID As String = SelectedRow.Cells("序号").Tag
                                Dim ConnRun_SP_ID As String = SelectedRow.Cells("分支管").Tag     '中间conntoprocess线的ID
                                Dim Size As String : Dim SizeInSPI As String

                                With SelectedRow
                                    '离线仪表的情况

                                    Size = SelectedRow.Cells("分支管").Value
                                    SizeInSPI = SelectedRow.Cells("分支管（SPI）").Value
                                    If Not SizeSame(Size, SizeInSPI) Then
                                        UpdateConntoProcessSize(SelectedRow.Cells("位号").Value, ConnRun_SP_ID, Size, SizeInSPI, SP_ID)
                                    End If


                                End With

                                '***********Config.xml中的其他属性
                                For j = .Columns.IndexOf("图纸号") + 1 To .Columns.Count - 1 Step 2
                                    If Not SelectedRow.Cells(j + 1).Value Is Nothing Then
                                        'If SPIDataColumns.IndexOf(.Columns(j).Name + "@4") > -1 Then
                                        '    UpdateMoreProp(SP_ID, SelectedRow.Cells(j + 1).Value.ToString, SPIDataColumns(SPIDataColumns.IndexOf(.Columns(j).Name + "@4") + 1))

                                        'End If
                                        Dim PropName = .Columns(j).Name
                                        Dim FoundProps = SPIDataProps.Where(Function(x) x.ProcessFunction = myCatalogIndex.Pressure And x.PropName = PropName)
                                        If FoundProps.Count = 1 Then
                                            UpdateMoreProp(SP_ID, SelectedRow.Cells(j + 1).Value.ToString, FoundProps(0).UIDPID)
                                        End If
                                    End If
                                Next


                                DS.CommitTransaction()
                            Catch

                            End Try
                            SelectedRow.Cells(0).Value = False
                        Next

                    End With
                Case myCatalogIndex.Level
                    '---------液位
                    With RadPageGridList.Item(myCatalogIndex.Level)

                        For Each SelectedRow As GridViewRowInfo In .Rows.AsEnumerable().Where(Function(x) x.Cells(0).Value = True).ToList
                            Try
                                DS.BeginTransaction()
                                Dim SP_ID As String = SelectedRow.Cells("序号").Tag
                                Dim ConnRun_SP_ID As String = SelectedRow.Cells("分支管").Tag     '中间conntoprocess线的ID
                                Dim Size As String : Dim SizeInSPI As String

                                With SelectedRow
                                    '离线仪表的情况

                                    Size = SelectedRow.Cells("分支管").Value
                                    SizeInSPI = SelectedRow.Cells("分支管（SPI）").Value
                                    If Not SizeSame(Size, SizeInSPI) Then
                                        UpdateConntoProcessSize(SelectedRow.Cells("位号").Value, ConnRun_SP_ID, Size, SizeInSPI, SP_ID)
                                    End If


                                End With

                                '***********Config.xml中的其他属性
                                For j = .Columns.IndexOf("图纸号") + 1 To .Columns.Count - 1 Step 2
                                    If Not SelectedRow.Cells(j + 1).Value Is Nothing Then
                                        'If SPIDataColumns.IndexOf(.Columns(j).Name + "@5") > -1 Then
                                        '    UpdateMoreProp(SP_ID, SelectedRow.Cells(j + 1).Value.ToString, SPIDataColumns(SPIDataColumns.IndexOf(.Columns(j).Name + "@5") + 1))

                                        'End If
                                        Dim PropName = .Columns(j).Name
                                        Dim FoundProps = SPIDataProps.Where(Function(x) x.ProcessFunction = myCatalogIndex.Level And x.PropName = PropName)
                                        If FoundProps.Count = 1 Then
                                            UpdateMoreProp(SP_ID, SelectedRow.Cells(j + 1).Value.ToString, FoundProps(0).UIDPID)
                                        End If
                                    End If
                                Next


                                DS.CommitTransaction()
                            Catch

                            End Try
                            SelectedRow.Cells(0).Value = False
                        Next

                    End With
                Case Else

            End Select







        Next
        ' objPIDAutoApp.Quit()







    End Sub

    ''' <summary>
    ''' 如果spi和pid的值不一样，就涂色
    ''' </summary>
    ''' <param name="cell"></param>
    ''' <param name="cellSpi"></param>
    ''' <remarks></remarks>
    Sub SetBackColorIfValuesDiff(ByRef cell As GridViewCellInfo, ByRef cellSpi As GridViewCellInfo)

        If cell.ColumnInfo.Name = cellSpi.ColumnInfo.Name.Replace("（SPI）", "") Then
            Try





                Dim value1 As String = IIf(IsNothing(cell.Value), "", cell.Value.ToString)
                Dim value2 As String = IIf(IsNothing(cellSpi.Value), "", cellSpi.Value.ToString)
                '特殊的
                If cell.ColumnInfo.Name = "公称直径" Or cell.ColumnInfo.Name = "分支管" Then
                    If SizeSame(value1, value2) Then
                        Exit Sub
                    End If
                End If
                If value2.Trim.Replace(" ", "") = "" And value1.Trim.Replace(" ", "") = "" Then
                    Exit Sub
                End If
                Select Case cell.ColumnInfo.Name
                    Case "执行机构"
                        value2 = GetStrFromXml(oRootNode, "SPIDataActuator", "Enum", value2)
                        value2 = value2.Substring(value2.LastIndexOf("\") + 1)
                    Case "阀体形式"
                        value2 = GetStrFromXml(oRootNode, "SPIDataType", "Enum", value2)
                        value2 = value2.Substring(value2.LastIndexOf("\") + 1)
                    Case "仪表类型"
                        value2 = GetStrFromXml(oRootNode, "SPIDataType", "Enum", value2)
                        value2 = value2.Substring(value2.LastIndexOf("\") + 1)
                    Case Else

                End Select

                If value2.Trim.Replace(" ", "") <> value1.Trim.Replace(" ", "") Then
                    'cellSpi.Style.ForeColor = Color.OrangeRed
                    'Dim myFont As New Font(New FontFamily("Calibri"), 12.0F, FontStyle.Italic)

                    'cellSpi.Style.Font = myFont
                    StyleCell(cellSpi)
                End If
            Catch ex As Exception

            End Try
        End If
    End Sub

    ''' <summary>
    ''' 反向数据流
    ''' </summary>
    ''' <param name="RadPageGridList"></param>
    ''' <remarks></remarks>
    Sub ReadData(ByRef RadPageGridList As List(Of RadGridView))
        Try
            Dim IfINIok As Boolean
            IfINIok = ReadConfigXml(RadPageGridList)
            If Not IfINIok Then
                '没找到ini文件
                MessageBox.Show("未检测到Config.xml文件 或 该xml文件内容有误，将结束。")
                Exit Sub
            End If

            DrawingCol.Clear()
            Dim DwgIDs As String = ""
            GetDwgCol(DS, DrawingCol, DwgIDs)
            If DrawingCol.Count = 0 Then
                '图纸一张都没选
                MessageBox.Show("您没有选择图纸！")
                Exit Sub
            End If

            For index = 0 To RadPageGridList.Count - 1
                RadPageGridList.Item(index).Rows.Clear()
            Next

            Dim dtInss As New DataTable : Dim dtConnToProcess As New DataTable : Dim dtActuator_BodyType As New DataTable : Dim dtCodeIndex As New DataTable
            SelectStr = "SELECT distinct T.SP_ID,T2.SP_DRAWINGID,T3.NAME FROM xxxSchemaName.T_INSTRUMENT T JOIN xxxSchemaName.T_REPRESENTATION T2 ON T2.SP_MODELITEMID=T.SP_ID JOIN xxxSchemaName.T_DRAWING T3 ON T3.SP_ID=T2.SP_DRAWINGID WHERE T2.SP_DRAWINGID IN (" + DwgIDs + ")"
            MyPIDConn.PIDReadDataByDBA(MyPIDConn.PIDPlant_DBNAME, MyPIDConn.ActivePlantPIDApp_User, SelectStr, dtInss)
            SelectStr = <string>select t3.sp_id,t3.itemtag,t10.sp_id spid1,t10.itemtag as tag1,t11.nominaldiameter,t8.itemtypename type2,t8.sp_id spid2,t6.itemtag Tag2,t12.path
         from xxxSchemaName.t_instrument t
         join xxxSchemaName.t_plantitem t3 on t.sp_id=t3.sp_id
         join xxxSchemaName.t_modelitem t7 on t7.sp_id=t3.sp_id
         join xxxSchemaName.t_representation t2 on t.sp_id=t2.sp_modelitemid
        left join xxxSchemaName.t_connector t4 on t4.sp_connectitem1id = t2.sp_id
        left join xxxSchemaName.t_representation t9 on t9.sp_id=t4.sp_id
        left join xxxSchemaName.t_plantitem t10 on t9.sp_modelitemid=t10.sp_id
        left join xxxSchemaName.t_representation t5 on t4.sp_connectitem2id=t5.sp_id
        left join xxxSchemaName.t_plantitem t6 on t5.sp_modelitemid=t6.sp_id
        left join xxxSchemaName.t_modelitem t8 on t8.sp_id=t6.sp_id
        left join xxxSchemaName.t_piperun t11 on t11.sp_id=t10.sp_id
        join xxxSchemaName.T_Drawing t12 on t12.SP_ID=t9.SP_DrawingID
        where t.isinline=1 and t8.itemtypename in ('PipeRun','Nozzle') and t3.itemtag is not null and t2.SP_DrawingID in (xxxstrDwgIDs)

                union

        select  t3.sp_id,t3.itemtag,t10.sp_id spid1,       t10.itemtag as tag1,t11.nominaldiameter,        t8.itemtypename type2,t8.sp_id spid2,t6.itemtag Tag2,t12.path
         from xxxSchemaName.t_instrument t
         join xxxSchemaName.t_plantitem t3 on t.sp_id=t3.sp_id
         join xxxSchemaName.t_modelitem t7 on t7.sp_id=t3.sp_id
         join xxxSchemaName.t_representation t2 on t.sp_id=t2.sp_modelitemid
        left join xxxSchemaName.t_connector t4 on t4.sp_connectitem2id = t2.sp_id
        left join xxxSchemaName.t_representation t9 on t9.sp_id=t4.sp_id
        left join xxxSchemaName.t_plantitem t10 on t9.sp_modelitemid=t10.sp_id
        left join xxxSchemaName.t_representation t5 on t4.sp_connectitem1id=t5.sp_id
        left join xxxSchemaName.t_plantitem t6 on t5.sp_modelitemid=t6.sp_id
        left join xxxSchemaName.t_modelitem t8 on t8.sp_id=t6.sp_id
     left join xxxSchemaName.t_piperun t11 on t11.sp_id=t10.sp_id
join xxxSchemaName.T_Drawing t12 on t12.SP_ID=t9.SP_DrawingID
        where t.isinline=1 and t8.itemtypename in ('PipeRun','Nozzle') and t3.itemtag is not null and t2.SP_DrawingID in (xxxstrDwgIDs)
</string>.Value.Replace("xxxstrDwgIDs", DwgIDs)  '用于查离线仪表的分支管
            SelectStr = <STRING>
SELECT t.sp_id connid,T3.SP_ID,T6.ITEMTAG,t6.sp_id insid,t7.nominaldiameter FROM xxxSchemaName.T_CONNECTOR T
JOIN xxxSchemaName.T_REPRESENTATION T2 ON T2.SP_ID=T.SP_ID
JOIN xxxSchemaName.T_MODELITEM T3 ON T3.SP_ID=T2.SP_MODELITEMID
JOIN xxxSchemaName.T_REPRESENTATION T4 ON T4.SP_ID=T.SP_CONNECTITEM1ID
JOIN xxxSchemaName.T_INSTRUMENT T5 ON T5.SP_ID=T4.SP_MODELITEMID
JOIN xxxSchemaName.T_PLANTITEM T6 ON T6.SP_ID=T5.SP_ID
join xxxSchemaName.t_piperun t7 on t7.sp_id=t2.sp_modelitemid
WHERE T3.ITEMTYPENAME='PipeRun' AND T5.ISINLINE=1 AND T6.ITEMTAG IS NOT NULL AND T4.SP_DRAWINGID in (xxxstrDwgIDs)
UNION
SELECT t.sp_id connid,T3.SP_ID,T6.ITEMTAG,t6.sp_id insid,t7.nominaldiameter FROM xxxSchemaName.T_CONNECTOR T
JOIN xxxSchemaName.T_REPRESENTATION T2 ON T2.SP_ID=T.SP_ID
JOIN xxxSchemaName.T_MODELITEM T3 ON T3.SP_ID=T2.SP_MODELITEMID
JOIN xxxSchemaName.T_REPRESENTATION T4 ON T4.SP_ID=T.SP_CONNECTITEM2ID
JOIN xxxSchemaName.T_INSTRUMENT T5 ON T5.SP_ID=T4.SP_MODELITEMID
JOIN xxxSchemaName.T_PLANTITEM T6 ON T6.SP_ID=T5.SP_ID
join xxxSchemaName.t_piperun t7 on t7.sp_id=t2.sp_modelitemid
WHERE T3.ITEMTYPENAME='PipeRun' AND T5.ISINLINE=1 AND T6.ITEMTAG IS NOT NULL AND T4.SP_DRAWINGID in (xxxstrDwgIDs)                          
                      </STRING>.Value.Replace("xxxstrDwgIDs", DwgIDs)  '2022 05 20，如果一个仪表有2个conn to process，就有2行
            MyPIDConn.PIDReadDataByDBA(MyPIDConn.PIDPlant_DBNAME, MyPIDConn.ActivePlantPIDApp_User, SelectStr, dtConnToProcess)
            SelectStr = <string>SELECT codelist_index      ,codelist_text      ,codelist_short_text  FROM xxxSchemaName.codelists
    where codelist_number = '8'
</string>.Value
            MyPIDConn.PIDReadDataByDBA(MyPIDConn.PIDPlant_DBNAME, MyPIDConn.ActivePlantPIDAppDictionary_User, SelectStr, dtCodeIndex)
            SelectStr = <string>
                        select t2.sp_id,t2.itemtag,t4.NominalDiameter,t5.Path,t8.sp_id ActSymID,t8.filename,t6.sp_id SymID,t6.filename TypeName
        from xxxSchemaName.t_instrument t1
        join xxxSchemaName.t_modelitem t3 on t1.sp_id=t3.sp_id
        join xxxSchemaName.t_plantitem t2 on t1.sp_id=t2.sp_id
        join xxxSchemaName.t_representation t6 on t6.sp_modelitemid=t1.sp_id
        left join xxxSchemaName.t_inlinecomp t4 on t4.sp_id=t1.sp_id
    join xxxSchemaName.T_Drawing t5 on t5.SP_ID=t6.SP_DrawingID
    left join xxxSchemaName.t_plantitem t7 on t2.sp_id=t7.sp_partofid
    left join xxxSchemaName.t_representation t8 on t8.sp_modelitemid=t7.sp_id
        where t2.itemtag is not null and t1.IsInline=2 and t6.SP_DrawingID in (xxxstrDwgIDs)
                    </string>.Value.Replace("xxxstrDwgIDs", DwgIDs)
            MyPIDConn.PIDReadDataByDBA(MyPIDConn.PIDPlant_DBNAME, MyPIDConn.ActivePlantPIDApp_User, SelectStr, dtActuator_BodyType)

            '项目是公制还是英制


            CallResult = LogInSPF()
            If CallResult <> "" Then
                MessageBox.Show(CallResult)
                Exit Sub
            End If

            Dim dtSPF As New DataTable
            Try
                LoadSPIDataFromSPF(dtSPF, DwgIDs, oRootNode)
            Catch ex As Exception
                Writelog("DataFromSPIToPID.vb的过程LoadSPIDataFromSPF有问题.  " + System.Reflection.MethodBase.GetCurrentMethod.Name, "反向数据流")
            End Try

            'Me.RadProgressBarElement1.Minimum = 0 : Me.RadProgressBarElement1.Maximum = DwgCol.Count - 1
            Dim oIns As LMInstrument : Dim i As Integer
            For i = 0 To DrawingCol.Count - 1
                For Each drIns As DataRow In dtInss.Select("SP_DRAWINGID='" + DrawingCol(i).ToString + "'")
                    oIns = DS.GetInstrument(drIns("SP_ID"))
                    If IsNothing(oIns) Then
                        Continue For
                    End If

                    '把离线仪表的dn换为connto process
                    Dim ConnToProcess As String = "" : Dim ConnToProcessConnectIDs As String = "" '就是连接到ins上的第一个id，可能有多个，所以是个集合

                    For Each drOffLine As DataRow In dtConnToProcess.Select("insid='" + drIns("SP_ID") + "'")
                        ConnToProcess = drOffLine("nominaldiameter").ToString
                        ConnToProcessConnectIDs += drOffLine("connid").ToString + ","
                        If ConnToProcess.Trim <> "" Then
                            For Each FoundRows As DataRow In dtCodeIndex.Select(String.Format("codelist_index = '{0}'", ConnToProcess))   'codeindex 换成 value
                                ConnToProcess = FoundRows("codelist_text").ToString
                                Exit For
                            Next
                        End If
                    Next
                    If Not ConnToProcessConnectIDs = "" Then
                        ConnToProcessConnectIDs = Mid(ConnToProcessConnectIDs, 1, Len(ConnToProcessConnectIDs) - 1)
                    End If


                    Dim InsRow As GridViewDataRowInfo
                    '决定放到哪个子表
                    For Each drSPF As DataRow In dtSPF.Select("OBJECT_REMOTE_UID='" + drIns("SP_ID") + "'")
                        Application.DoEvents()
                        'Me.RadProgressBarElement1.Value1 = i '"第 " + i.ToString + " 张图纸，对象SPID：" + oIns.Id.ToString
                        'Me.RadProgressBarElement1.Text = "第 " + i.ToString + " 张图纸，对象SPID：" + oIns.Id.ToString
                        Dim subGrid As RadGridView
                        Select Case drSPF("Proc_Func") + "," + drSPF("IsInline")
                            Case "Control Valve,PIDInlineInstrument"
                                subGrid = RadPageGridList.Item(myCatalogIndex.ControlValve)
                                '阀门的actutor   BodyType
                                Dim ActuatorInPid As String = "" : Dim BodyTypeInPid As String = ""
                                For Each drActuator_BodyType As DataRow In dtActuator_BodyType.Select("sp_id='" + drIns("SP_ID") + "'")
                                    ActuatorInPid = drActuator_BodyType("filename").ToString : BodyTypeInPid = drActuator_BodyType("TypeName").ToString
                                    Exit For
                                Next
                                '还要额外去拿执行机构和阀体的类型

                                InsRow = New GridViewDataRowInfo(subGrid.MasterView)
                                InsRow.Cells("公称直径").Value = GetAPIValue(oIns.Attributes("NominalDiameter").Value)
                                InsRow.Cells("公称直径（SPI）").Value = drSPF("DIM_INLET_SIZE").ToString
                                InsRow.Cells("执行机构").Value = Mid(ActuatorInPid, 1 + InStrRev(ActuatorInPid, "\")) : InsRow.Cells(4).Tag = ActuatorInPid
                                InsRow.Cells("执行机构（SPI）").Value = drSPF("执行机构").ToString '换成xml里的对应enum
                                InsRow.Cells("阀体形式").Value = Mid(BodyTypeInPid, 1 + InStrRev(BodyTypeInPid, "\")) : InsRow.Cells(6).Tag = BodyTypeInPid
                                InsRow.Cells("阀体形式（SPI）").Value = drSPF("阀体形式").ToString '换成xml里的对应enum

                                'ini中灵活的属性。gridview中的column名字，为xml中的第一段。dtSPF中的column名字，为xml的第一段+（SPI）。API查询的是xml中的第二段。dtSPF查询的是xml中的第三段
                                '因为图纸号是grid里最后一个column
                                For j = subGrid.Columns.IndexOf("图纸号") + 1 To subGrid.Columns.Count - 1 Step 2
                                    'InsRow.Cells(j).Value = GetAPIValue(oIns.Attributes(SPIDataColumns(SPIDataColumns.IndexOf(RadPageGridList.Item(0).Columns(j).Name + "@1") + 1)).Value)
                                    'InsRow.Cells(j + 1).Value = drSPF(RadPageGridList.Item(0).Columns(j).Name + "@1" + "（SPI）").ToString
                                    'SetBackColorIfValuesDiff(InsRow.Cells(j), InsRow.Cells(j + 1))
                                    Dim PropName = subGrid.Columns(j).Name
                                    Dim FoundProps = SPIDataProps.Where(Function(x) x.ProcessFunction = myCatalogIndex.ControlValve And x.PropName = PropName)
                                    If FoundProps.Count = 1 Then
                                        InsRow.Cells(j).Value = GetAPIValue(oIns.Attributes(FoundProps(0).UIDPID).Value)
                                        InsRow.Cells(j + 1).Value = drSPF(FoundProps(0).PropName + "@" + FoundProps(0).ProcessFunction.ToString + "（SPI）")
                                        InsRow.Cells(j + 1).Value = IIf(IsNothing(InsRow.Cells(j + 1).Value), "", InsRow.Cells(j + 1).Value)
                                    End If
                                Next
                            Case "Flow Instrument,PIDInlineInstrument"
                                subGrid = RadPageGridList.Item(myCatalogIndex.Flow)
                                '流量计的类型
                                Dim FlowType As String = ""
                                For Each drFlowMeter As DataRow In dtActuator_BodyType.Select("sp_id='" + drIns("SP_ID") + "'")
                                    FlowType = drFlowMeter("TypeName").ToString
                                    Exit For
                                Next

                                InsRow = New GridViewDataRowInfo(subGrid.MasterView)
                                InsRow.Cells("公称直径").Value = GetAPIValue(oIns.Attributes("NominalDiameter").Value)
                                InsRow.Cells("公称直径（SPI）").Value = drSPF("DIM_INLET_SIZE").ToString
                                InsRow.Cells("仪表类型").Value = Mid(FlowType, 1 + InStrRev(FlowType, "\")) : InsRow.Cells(6).Tag = FlowType
                                InsRow.Cells("仪表类型（SPI）").Value = drSPF("阀体形式").ToString '换成xml里的对应enum
                                'ini中灵活的属性
                                For j = subGrid.Columns.IndexOf("图纸号") + 1 To subGrid.Columns.Count - 1 Step 2
                                    'InsRow.Cells(j).Value = GetAPIValue(oIns.Attributes(SPIDataColumns(SPIDataColumns.IndexOf(RadPageGridList.Item(1).Columns(j).Name + "@2") + 1)).Value)
                                    'InsRow.Cells(j + 1).Value = drSPF(RadPageGridList.Item(1).Columns(j).Name + "@2" + "（SPI）").ToString
                                    Dim PropName = subGrid.Columns(j).Name
                                    Dim FoundProps = SPIDataProps.Where(Function(x) x.ProcessFunction = myCatalogIndex.Flow And x.PropName = PropName)
                                    If FoundProps.Count = 1 Then
                                        InsRow.Cells(j).Value = GetAPIValue(oIns.Attributes(FoundProps(0).UIDPID).Value)
                                        InsRow.Cells(j + 1).Value = drSPF(FoundProps(0).PropName + "@" + FoundProps(0).ProcessFunction.ToString + "（SPI）")
                                        InsRow.Cells(j + 1).Value = IIf(IsNothing(InsRow.Cells(j + 1).Value), "", InsRow.Cells(j + 1).Value)
                                    End If
                                Next
                            Case "Temperature Instrument,PIDInstrument"
                                subGrid = RadPageGridList.Item(myCatalogIndex.Temperature)
                                InsRow = New GridViewDataRowInfo(subGrid.MasterView)
                                InsRow.Cells("分支管").Value = ConnToProcess : InsRow.Cells("分支管").Tag = ConnToProcessConnectIDs
                                InsRow.Cells("分支管（SPI）").Value = drSPF("ConnToProcess").ToString
                                'ini中灵活的属性
                                For j = subGrid.Columns.IndexOf("图纸号") + 1 To subGrid.Columns.Count - 1 Step 2
                                    'InsRow.Cells(j).Value = GetAPIValue(oIns.Attributes(SPIDataColumns(SPIDataColumns.IndexOf(RadPageGridList.Item(2).Columns(j).Name + "@3") + 1)).Value)
                                    'InsRow.Cells(j + 1).Value = drSPF(RadPageGridList.Item(2).Columns(j).Name + "@3" + "（SPI）").ToString
                                    Dim PropName = subGrid.Columns(j).Name
                                    Dim FoundProps = SPIDataProps.Where(Function(x) x.ProcessFunction = myCatalogIndex.Temperature And x.PropName = PropName)
                                    If FoundProps.Count = 1 Then
                                        InsRow.Cells(j).Value = GetAPIValue(oIns.Attributes(FoundProps(0).UIDPID).Value)
                                        InsRow.Cells(j + 1).Value = drSPF(FoundProps(0).PropName + "@" + FoundProps(0).ProcessFunction.ToString + "（SPI）")
                                        InsRow.Cells(j + 1).Value = IIf(IsNothing(InsRow.Cells(j + 1).Value), "", InsRow.Cells(j + 1).Value)
                                    End If
                                Next
                            Case "Pressure Instrument,PIDInstrument"
                                subGrid = RadPageGridList.Item(myCatalogIndex.Pressure)
                                InsRow = New GridViewDataRowInfo(subGrid.MasterView)
                                InsRow.Cells("分支管").Value = ConnToProcess : InsRow.Cells("分支管").Tag = ConnToProcessConnectIDs
                                InsRow.Cells("分支管（SPI）").Value = drSPF("ConnToProcess").ToString
                                'ini中灵活的属性
                                For j = subGrid.Columns.IndexOf("图纸号") + 1 To subGrid.Columns.Count - 1 Step 2
                                    'InsRow.Cells(j).Value = GetAPIValue(oIns.Attributes(SPIDataColumns(SPIDataColumns.IndexOf(RadPageGridList.Item(3).Columns(j).Name + "@4") + 1)).Value)
                                    'InsRow.Cells(j + 1).Value = drSPF(RadPageGridList.Item(3).Columns(j).Name + "@4" + "（SPI）").ToString
                                    Dim PropName = subGrid.Columns(j).Name
                                    Dim FoundProps = SPIDataProps.Where(Function(x) x.ProcessFunction = myCatalogIndex.Pressure And x.PropName = PropName)
                                    If FoundProps.Count = 1 Then
                                        InsRow.Cells(j).Value = GetAPIValue(oIns.Attributes(FoundProps(0).UIDPID).Value)
                                        InsRow.Cells(j + 1).Value = drSPF(FoundProps(0).PropName + "@" + FoundProps(0).ProcessFunction.ToString + "（SPI）")
                                        InsRow.Cells(j + 1).Value = IIf(IsNothing(InsRow.Cells(j + 1).Value), "", InsRow.Cells(j + 1).Value)
                                    End If
                                Next
                            Case "Level Instrument,PIDInstrument"
                                subGrid = RadPageGridList.Item(myCatalogIndex.Level)
                                InsRow = New GridViewDataRowInfo(subGrid.MasterView)
                                InsRow.Cells("分支管").Value = ConnToProcess : InsRow.Cells("分支管").Tag = ConnToProcessConnectIDs
                                InsRow.Cells("分支管（SPI）").Value = drSPF("ConnToProcess").ToString
                                'ini中灵活的属性
                                For j = subGrid.Columns.IndexOf("图纸号") + 1 To subGrid.Columns.Count - 1 Step 2
                                    'InsRow.Cells(j).Value = GetAPIValue(oIns.Attributes(SPIDataColumns(SPIDataColumns.IndexOf(RadPageGridList.Item(4).Columns(j).Name + "@5") + 1)).Value)
                                    'InsRow.Cells(j + 1).Value = drSPF(RadPageGridList.Item(4).Columns(j).Name + "@5" + "（SPI）").ToString
                                    Dim PropName = subGrid.Columns(j).Name
                                    Dim FoundProps = SPIDataProps.Where(Function(x) x.ProcessFunction = myCatalogIndex.Level And x.PropName = PropName)
                                    If FoundProps.Count = 1 Then
                                        InsRow.Cells(j).Value = GetAPIValue(oIns.Attributes(FoundProps(0).UIDPID).Value)
                                        InsRow.Cells(j + 1).Value = drSPF(FoundProps(0).PropName + "@" + FoundProps(0).ProcessFunction.ToString + "（SPI）")
                                        InsRow.Cells(j + 1).Value = IIf(IsNothing(InsRow.Cells(j + 1).Value), "", InsRow.Cells(j + 1).Value)
                                    End If
                                Next
                        End Select


                        'add row to gridview
                        If Not IsNothing(InsRow) Then
                            InsRow.Cells("序号").Value = InsRow.ViewTemplate.Rows.Count + 1 : InsRow.Cells("序号").Tag = GetAPIValue(oIns.Attributes("SP_ID").Value)
                            InsRow.Cells("位号").Value = GetAPIValue(oIns.Attributes("itemtag").Value)
                            InsRow.Cells("图纸号").Value = drIns("NAME").ToString
                            InsRow.ViewTemplate.Rows.Add(InsRow)

                        End If

                        Exit For
                    Next



                Next
            Next
        Catch ex As Exception
            Writelog("DataFromSPIToPID.vb的过程ReadData有问题.  " + System.Reflection.MethodBase.GetCurrentMethod.Name, "反向数据流")
        End Try

    End Sub
End Module
